import 'package:flutter/material.dart';
import 'package:jd_shop/utils/ToastMsg.dart';
import 'package:super_player/super_player.dart';

import '../../services/ScreenAdaper.dart';
import 'VideoDownLoad.dart';

class VideoPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _VideoPageState();
  }
}

class _VideoPageState extends State<VideoPage> {
  TXVodPlayerController _controller = TXVodPlayerController();
  var _aspectRatio = 16 / 9;
  List<String> videoList = [];
  List<Widget> list = [];

  @override
  void initState() {
    super.initState();
    videoList.add(
        "https://www.apple.com/105/media/us/iphone-x/2017/01df5b43-28e4-4848-bf20-490c34a926a7/films/feature/iphone-x-feature-tpl-cc-us-20170912_1920x1080h.mp4");
    videoList.add("https://video.699pic"
        ".com/videos/99/62/66/a_678875aae335217369962669334.mp4");
    videoList.add(
        "https://video.699pic.com/videos/24/30/86/a_677cf78eb15a717362430867282.mp4");
    videoList.add(
        "https://video.699pic.com/videos/13/91/15/a_vsghGAsY6E3M1735139115444.mp4");
    videoList.add(
        "https://video.699pic.com/videos/61/90/06/a_677371be5747117356190063591.mp4");
    videoList.add(
        "https://video.699pic.com/videos/04/57/54/b_xQH3s5IKn1Vn1731045754.mp4");
    videoList.add(
        "https://video.699pic.com/videos/85/87/28/a_673a1128408d617318587282666.mp4");
    videoList.add(
        "https://video.699pic.com/videos/46/30/62/b_56FwNqnZsK0h1732463062.mp4");
    videoList.add(
        "https://video.699pic.com/videos/61/30/96/a_674593e857d3c17326130963613.mp4");
    videoList.add(
        "https://video.699pic.com/videos/86/05/50/a_9bCXnZ9IIsDD17318605504131.mp4");
    videoList.add(
        "https://video.699pic.com/videos/34/81/50/a_672304768eb2317303481505862.mp4");
    videoList.add(
        "https://video.699pic.com/videos/34/83/04/a_672305102ff3017303483041993.mp4");
    videoList.add(
        "https://video.699pic.com/videos/55/35/66/a_672626ded939217305535668914.mp4");
    videoList.add(
        "https://video.699pic.com/videos/28/38/70/a_66d5be1e9910417252838706285.mp4");
    for (int i = 0; i < videoList.length; i++) {
      list.add(SizedBox(
        height: ScreenAdapter.getScreenWidth() * 0.56,
        width: ScreenAdapter.getScreenWidth(),
        child: TXPlayerVideo(controller: _controller),
      ));
    }
    initPlayer();
    FTXVodPlayConfig playConfig = FTXVodPlayConfig();

    /// 设为true，可平滑切换码率, 设为false时，可提高多码率地址打开速度
    playConfig.smoothSwitchBitrate = true;
    _controller.setConfig(playConfig);
    playConfig.maxBufferSize = 1;
    //  播放时最大缓冲大小。单位：MB
    _controller.setConfig(playConfig);
    // 监听视频宽高变化，设置合适的宽高比例,也可自行设置宽高比例，视频纹理也会根据比例进行相应拉伸
    _controller.onPlayerNetStatusBroadcast.listen((event) async {
      double w = (event["VIDEO_WIDTH"]).toDouble();
      double h = (event["VIDEO_HEIGHT"]).toDouble();
      print("宽度 $w  高度  $h  ");
      if (w > 0 && h > 0) {
        setState(() {
          _aspectRatio = h / w;
        });
      }
    });

    _controller.onPlayerEventBroadcast.listen((event) async {
      if (event["event"] == TXVodPlayEvent.PLAY_EVT_PLAY_PROGRESS) {
        // 更多详细请查看iOS或者Android原生SDK状态码
        // 可播放时长，即加载进度, 单位是毫秒
        double playableDuration =
            event[TXVodPlayEvent.EVT_PLAYABLE_DURATION_MS].toDouble();
        // 播放进度, 单位是秒
        int progress = event[TXVodPlayEvent.EVT_PLAY_PROGRESS].toInt();
        // 视频总长, 单位是秒
        int duration = event[TXVodPlayEvent.EVT_PLAY_DURATION].toInt();
        print("duration  ${duration}  ${progress}  ${playableDuration}");
      }
      if (event["event"] == TXVodPlayEvent.PLAY_EVT_PLAY_END) {
        await _controller.stop();
        await _controller.resume();
      }
    });
  }

  initPlayer() async {
    VideoDownLoad().download(videoList);
    // 设置循环播放
    _controller.setLoop(true);
    // 初始化播放器，分配共享纹理
    await _controller.initialize();
    // 播放视频资源

    // await _controller.startVodPlay(_url);
    await _controller.setAutoPlay(isAutoPlay: true);
    await _controller.startVodPlay(videoList[0]);
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
    // 结束播放
    _controller.stop(isNeedClear: true);
  }

  // @override
  // Widget build(BuildContext context) {
  //   ScreenAdapter.init(context);
  //   return MediaQuery.removePadding(
  //       context: context,
  //       removeTop: true,
  //       child: Container(
  //         color: Colors.black,
  //         height: ScreenAdapter.getScreenHeight(),
  //         child: ListView.builder(
  //             itemCount: 10,
  //             itemBuilder: (context, index) {
  //               return Container(
  //                 color: Colors.red,
  //                 height: ScreenAdapter.getScreenHeight(),
  //                 width: ScreenAdapter.getScreenWidth(),
  //                 child: TXPlayerVideo(controller: _controller),
  //               );
  //             }),
  //       ));
  // }
  @override
  Widget build(BuildContext context) {
    ScreenAdapter.init(context);
    return Scaffold(
      body: Stack(
        children: [
          Container(
            color: Colors.black,
          ),
          Container(
            alignment: Alignment.center,
            child: SizedBox(
              height: ScreenAdapter.getScreenWidth() * _aspectRatio,
              child: PageView(
                scrollDirection: Axis.vertical,
                onPageChanged: (index) async {
                  print(index);
                  //无限加载
                  if (index + 2 == videoList.length) {
                    for (int i = 0; i < videoList.length; i++) {
                      list.add(Container(
                        // height: ScreenAdapter.getScreenHeight(),
                        width: ScreenAdapter.getScreenWidth(),
                        child: TXPlayerVideo(controller: _controller),
                      ));
                    }
                  }
                  await _controller.stop();
                  await _controller.enableHardwareDecode(true);
                  await _controller.startVodPlay(videoList[index]);
                  setState(() {});
                },
                children: list,
              ),
            ),
          )
        ],
      ),
    );
  }
}
